package com.tarena.lbs.activity.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.mapper.ActivityMapper;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.base.protocol.pager.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class ActivityRepositoryImpl implements ActivityRepository {

    @Autowired
    private ActivityMapper activityMapper;

    @DubboReference
    private AttachApi attachApi;


    /**
     * 分页查询活动列表
     * 使用PageHelper实现分页查询
     * @param query 查询参数
     * @return 活动列表分页结果
     */
    @Override
    public PageResult<ActivityVO> pageList(ActivityQuery query) {
        log.info("分页查询活动列表，参数：{}", query);
        QueryWrapper<ActivityPO> queryWrapper = assembleStoreQuery(query);
        // 使用PageHelper进行分页
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<ActivityPO> activityPOList = activityMapper.selectList(queryWrapper);
        // 转换为VO对象
        List<ActivityVO> activityVOList = new ArrayList<>();
        for (ActivityPO activityPO : activityPOList) {
            activityVOList.add(convertToVO(activityPO));
        }
        PageInfo<ActivityPO> pageInfo = new PageInfo<>(activityPOList);

        // 创建分页结果对象
        PageResult<ActivityVO> pageResult = new PageResult<>();
        pageResult.setObjects(activityVOList);
        pageResult.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        pageResult.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        pageResult.setTotal(pageInfo.getTotal());
        log.info("分页查询活动列表，结果数量：{}", activityVOList.size());
        return pageResult;
    }

    private QueryWrapper<ActivityPO> assembleStoreQuery(ActivityQuery query) {
        QueryWrapper<ActivityPO> queryWrapper = new QueryWrapper<>();
        if (query != null) {
            if (query.getActivityName() != null && !query.getActivityName().isEmpty()) {
                queryWrapper.eq("activity_name", query.getActivityName());
            }
            if (query.getDeliveryChannel() != null) {
                queryWrapper.eq("delivery_channel", query.getDeliveryChannel());
            }
            if (query.getType() != null) {
                queryWrapper.eq("type", query.getType());
            }
            if (query.getChannelType() != null) {
                queryWrapper.eq("channel_type", query.getChannelType());
            }
            if (query.getStatus() != null) {
                queryWrapper.eq("status", query.getStatus());
            }
            if (query.getStartDate() != null && !query.getStartDate().isEmpty()) {
                queryWrapper.ge("start_date", query.getStartDate());
            }
            if (query.getEndDate() != null && !query.getEndDate().isEmpty()) {
                queryWrapper.le("end_date", query.getEndDate());
            }
            if (query.getBusinessId() != null) {
                queryWrapper.eq("business_id", query.getBusinessId());
            }
        }
        return queryWrapper;
    }

    /**
     * 转换活动PO对象为VO对象
     * @param activityPO 活动PO对象
     * @return 活动VO对象
     */
    private ActivityVO convertToVO(ActivityPO activityPO) {
        if (activityPO == null) {
            return null;
        }
        // 这里可以添加一些额外的转换逻辑
        ActivityVO activityVO = new ActivityVO();
        BeanUtils.copyProperties(activityPO, activityVO);
        activityVO.setId(activityPO.getId().intValue());
        activityVO.setRewardCouponId(Integer.valueOf(activityPO.getRewardCouponId()));
        String[] imgIds = activityPO.getImgIds().split(",");
        List<Integer> imgIdsList = new ArrayList<>();
        for (String imgId : imgIds) {
            imgIdsList.add(Integer.valueOf(imgId.trim()));
        }
        List<AttachDTO> imgPics = attachApi.batchGetAttachInfo(imgIdsList, 1);
        List<String> imgPicUrls = new ArrayList<>();
        for (AttachDTO imgPic : imgPics) {
            imgPicUrls.add("http://localhost:9081/static/" + imgPic.getFileUuid());
        }
        activityVO.setImgPics(imgPicUrls);
        return activityVO;
    }

    /**
     * 添加活动
     * @param activityPO 活动PO对象
     */
    @Override
    public void addActivity(ActivityPO activityPO) {
        log.info("添加活动：{}", activityPO.getActivityName());
        activityPO.setRewardType(0); // 默认为普通活动
        activityPO.setEnableStatus(1);
        activityMapper.insert(activityPO);
        log.info("添加活动成功，ID：{}", activityPO.getId());
    }

    /**
     * 更新活动
     * @param activityPO 活动PO对象
     */
    @Override
    public void updateActivity(ActivityPO activityPO) {
        log.info("更新活动，ID：{}", activityPO.getId());
        activityMapper.update(activityPO, null);
        log.info("更新活动成功，ID：{}", activityPO.getId());
    }

    /**
     * 根据ID查询活动
     * @param id 活动ID
     * @param businessId 商家ID（可为null）
     * @return 活动PO对象
     */
    @Override
    public ActivityPO getActivityById(Long id, Integer businessId) {
        log.info("根据ID查询活动，ID：{}, businessId：{}", id, businessId);
        QueryWrapper<ActivityPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        if (businessId != null) {
            queryWrapper.eq("business_id", businessId);
        }
        return activityMapper.selectOne(queryWrapper);
    }

    @Override
    public List<ActivityPO> getActivityListByStoreId(Integer storeId) {
        QueryWrapper<ActivityPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("shop_ids", storeId);
        queryWrapper.eq("status", 1);
        return activityMapper.selectList(queryWrapper);
    }
}
